package com.heima.comment.service.impl;

import com.heima.aliyun.scan.GreenScan;
import com.heima.aliyun.scan.ScanResult;
import com.heima.comment.service.CommentRepayService;
import com.heima.common.exception.CustException;
import com.heima.feigns.UserFeign;
import com.heima.model.comment.dtos.CommentRepayDTO;
import com.heima.model.comment.dtos.CommentRepayLikeDTO;
import com.heima.model.comment.dtos.CommentRepaySaveDTO;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.comment.pojos.ApCommentRepayLike;
import com.heima.model.comment.vos.ApCommentVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

@Service
@Slf4j
public class CommentRepayServiceImpl implements CommentRepayService {
    @Autowired
    private GreenScan greenScan;

    @Autowired
    private UserFeign userFeign;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    RedissonClient redisson;

    /**
     * 查看更多回复内容
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadCommentRepay(CommentRepayDTO dto) {
        //校验参数
        //size为null 或 0 设置为10  最小日期为空 设置为当前
        if (dto.getMinDate() == null) {
            dto.setMinDate(new Date());
        }
        if (dto.getSize() == null || dto.getSize() == 0) {
            dto.setSize(10);
        }
        //条件查询评论回复信息
       //条件:  commentId = 评论id and createdTime 小于 minDate  创建时间 降序  limit size
        Query query = Query.query(Criteria.where("id").is(dto.getCommentId()).gt(dto.getMinDate()));
        query.limit(dto.getSize());//分页

        Sort sort = Sort.by(Sort.Direction.DESC, "createdTime");
        query.with(sort);// 排序
        //评论查询的数据
        List<ApCommentRepay> apCommentRepays = mongoTemplate.find(query, ApCommentRepay.class);
        //校验用户是否登录
        ApUser apUser = AppThreadLocalUtils.getUser();
        if (apUser == null) {
            return ResponseResult.okResult(apCommentRepays);
        }
        Query query1 = Query.query(Criteria.where("authorId").is(apUser.getId())
                .and("operation").is((short) 0));
        List<ApCommentRepayLike> apCommentRepayLikes = mongoTemplate.find(query1, ApCommentRepayLike.class);

        List<String> likeIds = new ArrayList<>();
        for (ApCommentRepayLike apCommentRepayLike : apCommentRepayLikes) {
            likeIds.add(apCommentRepayLike.getCommentRepayId());
        }
        ArrayList<ApCommentVo> commentVos = new ArrayList<>();
        for (ApCommentRepayLike apCommentRepayLike : apCommentRepayLikes) {
            ApCommentVo apCommentVo = new ApCommentVo();
            BeanUtils.copyProperties(apCommentRepayLike,apCommentVo);
            commentVos.add(apCommentVo);
        }
        //如果当前评论id在点赞记录中存在  设置operation字段为0
        for (ApCommentVo commentVo : commentVos) {
            if (likeIds.contains(commentVo.getId())) {
                commentVo.setOperation((short) 0);
            }
        }
        return ResponseResult.okResult(commentVos);

    }

    /**
     * 保存回复
     *
     * @return
     */
    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDTO dto) {
        //校验用户是否登录
        ApUser apUser = AppThreadLocalUtils.getUser();
        if (apUser == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //内容安全校验
        try {
            ScanResult scanResult = greenScan.greenTextScan(dto.getContent());
            String suggestion = scanResult.getSuggestion();
            switch (suggestion) {
                case "block":
                    log.error("评论信息含有违规内容 ===>原因：{}" + scanResult.getReason());
                    CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, scanResult.getReason());
                    break;
                case "review":
                    dto.setContent(scanResult.getFilteredContent());
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("阿里云文本审核出现异常 , 原因:{}", e.getMessage());
        }
        //根据评论id查询评论信息  检查是否存在
        Query query = Query.query(Criteria.where("id").is(dto.getCommentId()));
        ApComment apComment = mongoTemplate.findOne(query, ApComment.class);
        if (apComment == null) {
            CustException.cust(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST, "评论信息不存在");
        }
        //保存评论回复信息
        //远程查询当前登陆用户信息
        ResponseResult<ApUser> userReault = userFeign.findUserById(apUser.getId());
        if (!userReault.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        ApUser user = userReault.getData();
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setAuthorId(apUser.getId());
        apCommentRepay.setAuthorName(user.getName());
        apCommentRepay.setCommentId(apComment.getId());
        apCommentRepay.setContent(dto.getContent());
        apCommentRepay.setLikes(0);
        apCommentRepay.setLongitude(new BigDecimal("0"));
        apCommentRepay.setLatitude(new BigDecimal("0"));
        apCommentRepay.setAddress("");
        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setUpdatedTime(new Date());
        mongoTemplate.save(apCommentRepay);
        //修改评论信息中回复数量 + 1
        apComment=new ApComment();
        apComment.setReply(apComment.getReply() + 1);
        mongoTemplate.save(apComment);
        return ResponseResult.okResult();
    }

    /**
     * 点赞回复的评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDTO dto) {
        Map<String, Integer> map = new HashMap<>();
        //判断登录
        ApUser apUser = AppThreadLocalUtils.getUser();
        if (apUser == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //根据评论回复id查询评论数据， 为null返回错误信息
        Query commentRepayQuery = Query.query(Criteria.where("id").is(dto.getCommentRepayId()));
        ApCommentRepay commentRepay = mongoTemplate.findOne(commentRepayQuery, ApCommentRepay.class);
        if (commentRepay == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "评论回复信息不存在");
        }
        //获取回复点赞实体条件
        Query authorId = Query.query(Criteria.where("authorId")
                .is(apUser.getId()).and("commentRepayId").is(dto.getCommentRepayId())
                .and("operation").is((short) 0));
        //判断用户是否已经点赞
        RLock lock = redisson.getLock("likes-lock");
        lock.lock();
        try {
            ApCommentRepayLike apCommentRepayLike = mongoTemplate.findOne(authorId, ApCommentRepayLike.class);
            if (apCommentRepayLike != null && apCommentRepayLike.getOperation().intValue() == 0) {
                CustException.cust(AppHttpCodeEnum.DATA_EXIST, "请勿重复点赞");
            }
            if (dto.getOperation().intValue() == 0) {
                ApCommentRepayLike commentRepayLike = new ApCommentRepayLike();
                commentRepayLike.setAuthorId(apUser.getId());
                commentRepayLike.setCommentRepayId(dto.getCommentRepayId());
                commentRepayLike.setOperation((short) 0);
                mongoTemplate.save(commentRepayLike);
                //将回复信息的点赞数量字段+1
                commentRepay = new ApCommentRepay();
                commentRepay.setLikes(commentRepay.getLikes()+1);
                mongoTemplate.save(commentRepay);
                map.put("likes", commentRepay.getLikes());

            }else{
                commentRepay = new ApCommentRepay();
                commentRepay.setLikes(commentRepay.getLikes()-1);
                mongoTemplate.save(commentRepay);
                map.put("likes", commentRepay.getLikes());
            }
        } finally {
            lock.lock();
        }

        return ResponseResult.okResult(map);
    }
}
